export const uuid = () => {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        const r = Math.random() * 16 | 0;
        const v = c === 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

export const sleep = (delay = 100) => {
    return new Promise(resolve => setTimeout(resolve, delay));
}

export const clamp = (x: number, min: number, max: number) => {
    return x < min ? min : x > max ? max : x;
}

export const withResolvers = <T>(): {
    promise: Promise<T>;
    resolve: (value: T) => void;
    reject: (reason?: any) => void;
} => {
    let ref: any = {};
    let promise = new Promise<T>((resolve, reject) => {
        ref = { resolve, reject }
    })
    return {
        promise,
        resolve(value) {
            ref.resolve(value)
        },
        reject(reason) {
            ref.reject(reason)
        },
    }
}

export const inNeteaseAppFamily = () => {
    const ua = window.navigator.userAgent;
    return /CloudMusic\//.test(ua);
};

export const toLoopCount = (loop: number | boolean) => {
    let maxCount = loop as number;
    if (loop === false) {
        maxCount = 1;
    }
    if (loop === true) {
        maxCount = Infinity;
    }
    return maxCount;
}

export const removeElement = (el: Element) => {
    if (typeof el.remove === 'function') {
        el.remove();
    } else if (el.parentNode) {
        el.parentNode.removeChild(el);
    }
}
